#!/bin/bash

# collect information from node's logfiles and database
# create database trace.sqlite

scriptPath=$(dirname $0);

if [ -f trace.sqlite ]
then
	rm trace.sqlite
fi

if [ -f all-nodes.db ]
then
	rm all-nodes.db
fi

cat $scriptPath/createDatabase.sql.begin > trace.sql

for logPath in $(ls -1d */)
do
	logPath=$(echo $logPath | sed 's/\///')

	# --- device name

	# use name in title file, else folder name
	if [ -f $logPath/title ]
	then device=$(cat $logPath/title);
	else device=$logPath;
	fi
   	echo $device

	echo .. create sql


	# --- events
	# trace.log > all events
   	if [ -f $logPath/trace.log ]
	then
		awk -f $scriptPath/createDatabaseTrace.awk -v device="$device" $logPath/trace.log >> trace.sql
	fi


	# --- node information
	# haggle.db > nodeId (thisNode)
	sqlite3 -batch -separator ' ' $logPath/haggle.db "SELECT id_str FROM table_nodes WHERE type=1;" | awk -f $scriptPath/createDatabaseThisNode.awk -v device="$device" >> trace.sql

	# haggle.log > nodeId
#    	if [ -f $logPath/haggle.log ]
# 	then 
# 		awk -f $scriptPath/createDatabaseLog.awk -v device="$device" $logPath/haggle.log >> trace.sql
# 	fi

	# fallback in case haggle.log and thisNode is not available > below after the loop

	# haggle.db > applications
	sqlite3 -batch -separator ' ' $logPath/haggle.db "SELECT id_str, name FROM table_nodes WHERE type=2;" | awk -f $scriptPath/createDatabaseApplication.awk -v device="$device" >> trace.sql
	
	# --- global datastore
	# merge databases into all-nodes.sqlite
	if [ -f all-nodes.db ]
	then
		cp $logPath/haggle.db tmp.db
		sh $scriptPath/createDatabaseMerge.sh all-nodes.db tmp.db
		rm tmp.db
	else
		cp $logPath/haggle.db all-nodes.db
		sh $scriptPath/createDatabaseMergeBackupRowidMappings.sh all-nodes.db
	fi
	
done

# --- node information fallback

# all-nodes.db > nodeId
#   - used in case haggle.log and thisNode is missing
#   - note that this command uses the device name instead of the name of the directory. 
#   - also, only information about nodes that met other nodes is available. 
sqlite3 -batch -separator ' ' all-nodes.db "SELECT id_str, name FROM table_nodes WHERE type!=2;" | awk -f $scriptPath/createDatabaseNode.awk >> trace.sql


# --- create database

echo create database

# restore rowids in mappings
# sh $scriptPath/createDatabaseMergeRestoreRowidMappings.sh all-nodes.db

# sql end
cat $scriptPath/createDatabase.sql.end >> trace.sql

# create database trace.sqlite from collected information
echo filter database

sqlite3 -batch -separator ' ' trace.sqlite < trace.sql | sed 's/EVENT_TYPE_//g'

rm trace.sql


